package notify

import (
	"fmt"
	"fx_swift_boss/api"
	"fx_swift_boss/pkg/logger"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"go.uber.org/zap"
	"log"
	"net/http"
	"sync"
	"time"
)

var (
	// connected clients
	conns = make(map[string]*websocket.Conn)

	mu sync.RWMutex

	upgrader = websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
		CheckOrigin:     func(r *http.Request) (b bool) { return true },
	}
)

func SendMsgToWebStock(data *api.WedStockRes) {
	mu.RLock()
	for account, conn := range conns {
		if data.Account == account {
			if conn != nil {
				if err := conn.WriteJSON(data); err != nil {
					logger.Logger.Error("write json error", zap.Error(err))
				}
			}
		}
	}
	mu.RUnlock()
}

func SendKeepAlive() {
	for {
		time.Sleep(10 * time.Second)
		mu.RLock()
		for _, conn := range conns {
			if conn != nil {
				if err := conn.WriteMessage(1, []byte("")); err != nil {
					logger.Logger.Error("write json error", zap.Error(err))
				}
			}
		}
		mu.RUnlock()
	}
}

// Run is Websocket Server Run
func WebStockRun(c *gin.Context) {
	defer func() {
		if r := recover(); r != nil {
			// 这里打印panic信息，同时保证了主程序不会崩溃退出
			log.Println("Recovered in Run", r)
		}
	}()
	account := c.Query("account")
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil) // Upgrade HTTP server to WebSocket server
	if err != nil {
		logger.Logger.Error("notify upgrade error", zap.Error(err))
		return
	}
	defer conn.Close()

	//clientID := uuid.New() // 创建一个UUID作为客户端的唯一标识
	mu.Lock()
	conns[account] = conn // 将客户端连接添加到map中
	mu.Unlock()

	for {
		// Read message from browser
		_, msg, err := conn.ReadMessage()
		if err != nil {
			logger.Logger.Info("read message error", zap.Error(err))
			break
		}

		// Print the message to the console
		fmt.Printf("ip:%s uuid:%s sent: %v\n", conn.RemoteAddr(), account, string(msg))
	}

	mu.Lock()
	delete(conns, account) // 客户端连接关闭后，将其从map中移除
	mu.Unlock()
}
